Main site

Sample codes > Using collection name

Using collection name

As with any LLM AI model outputs, always verify the generated code for accuracy before deploying it live.

For the sample prompts here, your might get different responses since AI models have random elements.

AI Prompt:

Generate a shipping code that uses the item product collections. 
If the collection contains the name "Fragile", add $10 on the standard fee.  
The standard fee is $15. 
Print the error message.

AI Output:

// Import required modules from "./modules.js"
import { enrichItemDetails, print } from "./modules.js";

export async function calculateShippingRates(DATA, env) {
    try {
        // Enrich item details to access product collections
        DATA = await enrichItemDetails(DATA);

        // Standard shipping fee in cents
        const standardFee = 1500; // $15 in cents
        let additionalFee = 0;

        // Check each item for collection membership
        DATA.items.forEach(item => {
            if (item.product && item.product.collections && item.product.collections.list) {
                item.product.collections.list.forEach(collection => {
                    // Check for "Fragile" collection
                    if (collection.name === "Fragile") {
                        additionalFee = 1000; // $10 in cents
                    }
                });
            }
        });

        // Calculate total shipping fee
        const totalShippingFee = standardFee + additionalFee;

        // Prepare shipping rate
        const rates = [{
            service_name: "Standard Shipping",
            service_code: "STD",
            total_price: totalShippingFee.toString(),
            description: additionalFee > 0 ? "Standard Shipping + Fragile Item Surcharge" : "Standard Shipping",
            currency: DATA.currency,
            min_delivery_date: "", // Assuming no date info provided
            max_delivery_date: ""
        }];

        return { rates };
    } catch (error) {
        // Print and return error message in case of exceptions
        print("Error", error.message);
        return { 
            rates: [{
                service_name: "",
                service_code: "",
                total_price: null,
                description: "",
                currency: "",
                min_delivery_date: "",
                max_delivery_date: ""
            }]
        };
    }
}